<!-- src/views/hrms/recruitment/profile/form.vue -->
<template>
	<xn-form-container
		:title="formData.id ? '编辑推荐信息' : '新增推荐信息'"
		:width="600"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="推荐分公司" name="city">
						<a-select
							v-model:value="formData.city"
							placeholder="请选择推荐分公司"
							:options="branchCityOptions"
							:allowClear="true"
							@change="onCityChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="推荐职位" name="recommendedPositionCode">
						<a-select
							v-model:value="formData.recommendedPositionCode"
							placeholder="请选择职位"
							:options="positionOptions"
							:allowClear="true"
							:disabled="!formData.city"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="候选人姓名" name="candidateName">
						<a-input v-model:value="formData.candidateName" placeholder="请输入候选人姓名" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="推荐部门" name="recommendedDepartment">
						<DeptSelectTree v-model="formData.recommendedDepartment" ref="deptSelectRef" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="推荐项目" name="recommendedProject">
						<a-input v-model:value="formData.recommendedProject" placeholder="请输入推荐项目" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="简历等级" name="resumeLevel">
						<a-select
							v-model:value="formData.resumeLevel"
							placeholder="请选择简历等级"
							:options="resumeLevelOptions"
							:allowClear="true"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="简历来源" name="resumeSource">
						<a-select
							v-model:value="formData.resumeSource"
							placeholder="请选择简历来源"
							:options="resumeSourceOptions"
							:allowClear="true"
							@change="onResumeSourceChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="推荐人" name="recommenderId" :rules="recommenderRules">
						<a-input
							v-if="formData.resumeSource === 'INTERNAL_REFERRAL'"
							@click="userSelectorPlusRef.showUserPlusModal()"
							:value="selectedUser.name ? selectedUser.name : ''"
							placeholder="请选择推荐人"
							readonly
						/>
						<a-input v-else placeholder="仅内部推荐可选择" disabled />
					</a-form-item>
				</a-col>
			</a-row>

			<a-form-item label="简历附件" name="resumeFile">
				<a-upload
					name="resumeFile"
					:file-list="fileList"
					:before-upload="beforeUpload"
					:on-remove="handleRemove"
					:max-count="1"
					accept=".pdf,.doc,.docx,.jpg,.png"
				>
					<a-button>
						<upload-outlined />
						上传简历附件
					</a-button>
				</a-upload>

				<!-- 显示已上传文件信息 -->
				<div v-if="uploadedFileName" class="file-info" style="margin-top: 10px">
					<p>已选择文件: {{ uploadedFileName }}</p>
				</div>

				<!-- 编辑时显示原有文件信息和下载按钮 -->
				<div
					v-if="formData.id && formData.resumeAttachment && !uploadedFileName"
					class="file-preview"
					style="margin-top: 10px"
				>
					<p>
						当前文件: {{ getFileNameFromUrl(formData.resumeAttachment) || '简历附件' }}
						<a-button type="link" @click="downloadFile(formData.resumeAttachment)" size="small">下载 </a-button>
					</p>
				</div>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
		<UserSelectorPlus
			ref="userSelectorPlusRef"
			data-type="object"
			:user-show="false"
			:radio-model="true"
			@onBack="userCallBack"
		/>
	</xn-form-container>
</template>

<script setup>
	import { required } from '@/utils/formRules'
	import tool from '@/utils/tool'
	import recruitmentProfileApi from '@/api/hrms/recruitment/profile/recruitmentProfileApi'
	import { message } from 'ant-design-vue'
	import { UploadOutlined } from '@ant-design/icons-vue'
	import { computed, reactive, ref } from 'vue'
	import recruitmentPositionsApi from '@/api/hrms/recruitment/positions/recruitmentPositionsApi'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	// 引入新创建的部门选择组件
	import DeptSelectTree from '@/components/Selector/deptSelectTree.vue'

	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const userSelectorPlusRef = ref()
	const deptSelectRef = ref()
	const branchCityOptions = tool.dictList('BRANCH_CITY')
	const resumeLevelOptions = tool.dictList('RESUME_LEVEL')
	const resumeSourceOptions = tool.dictList('RESUME_SOURCE')
	const positionOptions = ref([])
	const fileList = ref([])
	const submitLoading = ref(false)

	// 存储按城市分组的职位数据
	const positionsGroupByCity = ref({})

	// 表单数据
	const formData = reactive({
		id: undefined,
		city: undefined,
		recommendedPositionCode: undefined,
		candidateName: undefined,
		recommendedDepartment: undefined,
		recommendedProject: undefined,
		resumeLevel: undefined,
		resumeSource: undefined,
		recommenderId: undefined,
		resumeAttachment: undefined
	})

	// 选中的推荐人信息
	const selectedUser = reactive({
		id: undefined,
		name: '',
		account: ''
	})

	// 推荐人验证规则
	const recommenderRules = computed(() => {
		if (formData.resumeSource === 'INTERNAL_REFERRAL') {
			return [{ required: true, message: '内部招聘必须选择推荐人' }]
		}
		return []
	})

	// 默认要校验的
	const formRules = {
		city: [required('请选择城市')],
		recommendedPositionCode: [required('请选择职位')],
		candidateName: [required('请输入候选人姓名')],
		recommendedDepartment: [required('请选择推荐部门')],
		resumeLevel: [required('请选择简历等级')],
		resumeSource: [required('请选择简历来源')]
	}

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		positionOptions.value = []
		// 获取按城市分组的职位数据
		recruitmentPositionsApi.getPositionsGroupByCity().then((res) => {
			positionsGroupByCity.value = res
			if (record) {
				Object.assign(formData, record)
				// 如果是内部招聘且有推荐人，设置推荐人信息
				if (record.resumeSource === 'INTERNAL_REFERRAL' && record.recommenderId) {
					// 设置推荐人信息
					selectedUser.id = record.recommenderId
					selectedUser.name = record.recommenderName || ''
				}
				// 如果有城市信息，更新职位选项
				if (record.city) {
					updatePositionOptions(record.city)
				}
			} else {
				// 新增时清空表单
				Object.keys(formData).forEach((key) => {
					formData[key] = undefined
				})
				// 清空选中的推荐人信息
				Object.keys(selectedUser).forEach((key) => {
					selectedUser[key] = undefined
				})
				positionOptions.value = []
				fileList.value = []
			}
		})

		if (!record) {
			// 新增时清空表单
			Object.keys(formData).forEach((key) => {
				formData[key] = undefined
			})
			// 清空选中的推荐人信息
			Object.keys(selectedUser).forEach((key) => {
				selectedUser[key] = undefined
			})
			positionOptions.value = []
			fileList.value = []
		}
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value?.resetFields()
		Object.keys(formData).forEach((key) => {
			formData[key] = undefined
		})
		Object.keys(selectedUser).forEach((key) => {
			selectedUser[key] = undefined
		})
		positionOptions.value = []
		fileList.value = []
		visible.value = false
		submitLoading.value = false
	}

	// 计算属性：获取上传的文件名
	const uploadedFileName = computed(() => {
		if (fileList.value.length > 0) {
			return fileList.value[0].name
		}
		return ''
	})

	const getFileNameFromUrl = (url) => {
		if (!url) return ''
		try {
			const urlObj = new URL(url)
			const pathname = urlObj.pathname
			const fileName = pathname.substring(pathname.lastIndexOf('/') + 1)
			return decodeURIComponent(fileName)
		} catch (e) {
			return '简历附件'
		}
	}

	// 下载文件
	const downloadFile = (fileUrl) => {
		const link = document.createElement('a')
		link.href = fileUrl
		link.download = getFileNameFromUrl(fileUrl)
		link.target = '_blank'
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)
	}

	// 根据城市更新职位选项
	const updatePositionOptions = (city) => {
		// 从分组数据中获取指定城市的职位列表
		const positionsInCity = positionsGroupByCity.value[city] || []
		positionOptions.value = positionsInCity.map((item) => ({
			label: item.name,
			value: item.code
		}))

		// 注意：不再清除已选择的职位，保持编辑时的回显
		// 如果当前选择的职位不在新城市中，则清空选择
		if (
			formData.recommendedPositionCode &&
			!positionOptions.value.some((option) => option.value === formData.recommendedPositionCode)
		) {
			formData.recommendedPositionCode = undefined
		}
	}

	const onCityChange = (city) => {
		if (!city) {
			positionOptions.value = []
			// 只有在新增时才清空职位选择，编辑时保持原值
			if (!formData.id) {
				formData.recommendedPositionCode = undefined
			}
			return
		}

		// 使用已获取的分组数据更新职位选项
		updatePositionOptions(city)
	}

	const onResumeSourceChange = (source) => {
		// 清空推荐人信息
		formData.recommenderId = undefined
		selectedUser.id = undefined
		selectedUser.name = ''
		selectedUser.account = ''

		// 清除推荐人字段的验证状态
		if (formRef.value) {
			// 使用 nextTick 确保在下次 DOM 更新后执行
			setTimeout(() => {
				// 手动清除字段的错误状态
				formRef.value.clearValidate(['recommenderId'])
			}, 0)
		}
	}

	const beforeUpload = (file) => {
		const isLt10M = file.size / 1024 / 1024 < 10
		if (!isLt10M) {
			message.error('文件大小不能超过 10MB!')
			return false
		}
		fileList.value = [file]
		return false
	}

	// 移除文件
	const handleRemove = () => {
		fileList.value = []
		return true
	}

	const userCallBack = (users) => {
		if (users && users.length > 0) {
			// 取第一条数据
			const user = users[0]
			selectedUser.id = user.id
			selectedUser.name = user.name
			selectedUser.account = user.account
			formData.recommenderId = user.id
		}
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true

				// 准备提交数据
				const submitFormData = { ...formData }

				// 如果不是内部推荐，删除推荐人相关字段
				if (formData.resumeSource !== 'INTERNAL_REFERRAL') {
					delete submitFormData.recommenderId
				}

				const submitData = new FormData()
				if (fileList.value.length > 0) {
					submitData.append('multipartFile', fileList.value[0])
				}
				submitData.append(
					'candidateProfileAddBo',
					new Blob([JSON.stringify(submitFormData)], { type: 'application/json' })
				)
				recruitmentProfileApi
					.insertOrEditWithFile(submitData)
					.then(() => {
						message.success(formData.id ? '修改成功' : '新增成功')
						onClose()
						emit('successful')
					})
					.catch((error) => {
						message.error((formData.id ? '修改失败: ' : '新增失败: ') + (error.message || ''))
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {
				submitLoading.value = false
			})
	}

	defineExpose({
		onOpen
	})
</script>

<style scoped>
	.file-info {
		color: #52c41a;
		font-size: 14px;
	}

	.file-preview {
		color: #1890ff;
		font-size: 14px;
	}

	.xn-wd {
		width: 100%;
	}
</style>
